
from subprocess import call

import numpy as np
from pdf2image import convert_from_bytes, convert_from_path
from PIL.PpmImagePlugin import PpmImageFile

from .. import lock

async def calculate_file(file_path: str | None=None, file_blob: bytes | None=None) -> list[bool]:
    page_color_list = []
    if file_path and not file_blob:
        photos: list[PpmImageFile] = convert_from_path(file_path)
    elif file_blob and not file_path:
        photos: list[PpmImageFile] = convert_from_bytes(file_blob)
    for photo in photos:
        page_color_list.append(await is_color_image(photo))
    return page_color_list

async def doc_to_pdf(input_path: str):
    args = ['libreoffice', '--headless', '--convert-to', 'pdf', input_path, '--outdir', './files']
    lock.acquire()
    try:
        code = call(args)
    finally:
        lock.release()
    return code

async def is_color_image(image: PpmImageFile, threshold: float=10) -> bool:

    if len(image.getbands()) == 1:
        return True
    
    images = [np.asarray(image.getchannel(channel=i), dtype=np.int16) for i in range(3)]
    diffs = [(images[i] - images[(i+1)%3]).var() for i in range(3)]
    
    return sum(diffs) / 3 > threshold
